package com.zhihuichongcheng.application.ui.task;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.task.TaskBean;
import com.zhihuichongcheng.application.bean.task.TaskPriority;
import com.zhihuichongcheng.application.bean.task.TaskType;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.net.HttpManager;
import com.zhihuichongcheng.application.ui.task.adapter.TaskAdapter;
import com.zhihuichongcheng.application.util.StringUtils;

import java.util.HashMap;
import java.util.List;

/**
 * 任务 Created by LK on 2017/1/5.
 */
public class TaskListActivity extends BaseActivity implements View.OnClickListener {
    public static final String ACTION_REFRESH_LIST = "intent.refresh.task.list";
    public static final String ACTION_NEW_TASK_MSG = "intent.new.task.msg";
    protected HttpManager manager;
    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            }
        }
    };
    private XRecyclerView mRecyclerView;
    private TextView itemFromMe, itemToMe, itemCopyMe, tvTaskMsgCount;
    private TaskAdapter mAdapter;
    private int currentPage = 1;
    private boolean hasNext = false;
    private int pageCount = 20;
    //筛选条件
    private int missionType = -1;
    private String userIds;
    private int priority = -1;
    private String finishTime;
    private IntentFilter intentFilter;
    private TaskReceiver receiver;
    private ListType currentListType = ListType.ToMe;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_list);
        manager = HttpManager.getInstance(this);
        registerReceiver();
        initViews();
        initListView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        requestMsgCount();
    }

    private void requestMsgCount() {
        HashMap<String, String> paramsDemo = new HashMap<>();
        paramsDemo.put("token", mUser.getToken());
        //筛选条件
        manager.post(NetworkAPI.MISSION_MSG_COUNT, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                int count = 0;
                if (!StringUtils.isEmpty(value)) {
                    count = Integer.parseInt(value);
                }

                tvTaskMsgCount.setText(count + "");
                tvTaskMsgCount.setVisibility(count == 0 ? View.GONE : View.VISIBLE);
            }

            @Override
            public void onFailure(String value) {
            }
        }, paramsDemo);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver();
    }

    public void unregisterReceiver() {
        if (null != receiver) {
            unregisterReceiver(receiver);
        }
    }

    private void initViews() {
        mRecyclerView = (XRecyclerView) this.findViewById(R.id.rv_task);
        mRecyclerView.setHasFixedSize(true);
        tvTaskMsgCount = (TextView) this.findViewById(R.id.tv_msg_count);

        this.findViewById(R.id.ic_back).setOnClickListener(this);
        this.findViewById(R.id.im_add_task).setOnClickListener(this);
        this.findViewById(R.id.im_task_filter).setOnClickListener(this);
        this.findViewById(R.id.im_task_notice_layout).setOnClickListener(this);
    }

    private void initListView() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);

        mAdapter = new TaskAdapter(this);
        mRecyclerView.setAdapter(mAdapter);

        //Header
        mRecyclerView.addHeaderView(getHeaderView());
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }

            @Override
            public void onLoadMore() {
                loadNextData();
            }
        });
    }

    private void loadNextData() {
        if (hasNext) {
            currentPage++;
            loadData();
        }
    }

    private View getHeaderView() {
        View headerView = LayoutInflater.from(mRecyclerView.getContext()).inflate(R.layout.view_task_list_header, mRecyclerView, false);
        itemFromMe = (TextView) headerView.findViewById(R.id.list_from_me);
        itemCopyMe = (TextView) headerView.findViewById(R.id.list_copy_me);
        itemToMe = (TextView) headerView.findViewById(R.id.list_to_me);

        setListType(currentListType);

        itemFromMe.setOnClickListener(this);
        itemCopyMe.setOnClickListener(this);
        itemToMe.setOnClickListener(this);
        return headerView;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ic_back:
                finish();
                break;
            case R.id.im_add_task:
                startActivity(TaskDetailActivity.class);
                break;
            case R.id.im_task_filter:
                startTaskFilterActivityForResult();
                break;
            case R.id.im_task_notice_layout:
                startActivity(TaskMsgActivity.class);
                break;
            case R.id.list_from_me:
                setListType(ListType.FromMine);
                break;
            case R.id.list_to_me:
                setListType(ListType.ToMe);
                break;
            case R.id.list_copy_me:
                setListType(ListType.CopyToMe);
                break;
        }
    }

    private void startTaskFilterActivityForResult() {
        Bundle bundle = new Bundle();
        bundle.putInt(TaskFilterActivity.EXTRA_LIST_TYPE, getListTypeCode(currentListType));
        if (missionType >= 0)
            bundle.putInt(TaskFilterActivity.EXTRA_DEFAULT_TASK_TYPE, missionType);
        if (!StringUtils.isEmpty(userIds))
            bundle.putString(TaskFilterActivity.EXTRA_DEFAULT_USER_IDS, userIds);
        if (priority >= 0)
            bundle.putInt(TaskFilterActivity.EXTRA_DEFAULT_TASK_LV, priority);
        if (!StringUtils.isEmpty(finishTime))
            bundle.putString(TaskFilterActivity.EXTRA_DEFAULT_FINISH_TIME, finishTime);
        startActivityForResult(TaskFilterActivity.class, TaskFilterActivity.REQUEST_CODE_GET_FILTER, bundle);
    }

    public void setListType(ListType listType) {
        currentListType = listType;
        itemCopyMe.setTextColor(getResources().getColor(R.color.color_333333));
        itemToMe.setTextColor(getResources().getColor(R.color.color_333333));
        itemFromMe.setTextColor(getResources().getColor(R.color.color_333333));

        if (listType == ListType.ToMe)
            itemToMe.setTextColor(getResources().getColor(R.color.color_3C87D8));
        else if (listType == ListType.FromMine)
            itemFromMe.setTextColor(getResources().getColor(R.color.color_3C87D8));
        else if (listType == ListType.CopyToMe)
            itemCopyMe.setTextColor(getResources().getColor(R.color.color_3C87D8));

        refreshData();
    }

    private int getListTypeCode(ListType type) {
        if (type == ListType.FromMine) {
            return 1;
        }
        if (type == ListType.CopyToMe) {
            return 3;
        }

        return 2;
    }

    private void refreshData() {
        currentPage = 1;
        hasNext = true;
        mRecyclerView.setLoadingMoreEnabled(true);
        requestTaskPriority();
        requestTaskType();
        loadData();
        requestMsgCount();
    }

    /**
     * 请求任务优先级列表
     */
    private void requestTaskPriority() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        manager.post(NetworkAPI.MISSION_PRIORITY, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<TaskPriority> priorityList = GsonUtil.paraeFromStringToList(value, TaskPriority.class);
                TaskBean.setTaskPriorities(priorityList);
            }

            @Override
            public void onFailure(String value) {
            }
        }, params);
    }

    /**
     * 请求任务类型列表
     */
    private void requestTaskType() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        manager.post(NetworkAPI.MISSION_TYPE, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<TaskType> taskTypeList = GsonUtil.paraeFromStringToList(value, TaskType.class);
                TaskBean.setTaskTypeList(taskTypeList);
            }

            @Override
            public void onFailure(String value) {
            }
        }, params);
    }

    private void loadData() {
        DialogUtil.showLoadDiadlog(mContext);
        HashMap<String, String> paramsDemo = new HashMap<>();
        paramsDemo.put("token", mUser.getToken());
        paramsDemo.put("curPage", currentPage + "");
        paramsDemo.put("pageRows", pageCount + "");
        paramsDemo.put("listType", "" + getListTypeCode(currentListType));
        //筛选条件
        if (missionType >= 0)
            paramsDemo.put("missionType", missionType + "");
        if (!StringUtils.isEmpty(userIds))
            paramsDemo.put("receiveUserId", userIds + "");
        if (priority >= 0)
            paramsDemo.put("priority", priority + "");
        if (!StringUtils.isEmpty(finishTime))
            paramsDemo.put("finishTime", finishTime + "");
        manager.post(NetworkAPI.MISSION_LIST, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(getContext());
                if (code == 2) {
                    ToastOpt.createToast(getContext(), msg);
                    return;
                }
                List<TaskBean> taskList = GsonUtil.paraeFromStringToList(value, TaskBean.class);
                if (currentPage == 1)
                    mAdapter.reSetData(taskList);
                else
                    mAdapter.setData(taskList);
                mAdapter.notifyDataSetChanged();
                mRecyclerView.refreshComplete();
                mRecyclerView.loadMoreComplete();
                if (taskList.size() < pageCount) {
                    hasNext = false;
                    mRecyclerView.setLoadingMoreEnabled(false);
                }
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(getContext(), "查询失败 " + value);
                DialogUtil.dismiss(getContext());
                mRecyclerView.refreshComplete();
                mRecyclerView.loadMoreComplete();
            }
        }, paramsDemo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TaskFilterActivity.REQUEST_CODE_GET_FILTER) {
            if (resultCode == BaseActivity.EXTRA_RESPONSE_CODE_SUCCESS) {
                Bundle bundle = data.getExtras();
                if (bundle.containsKey(TaskFilterActivity.EXTRA_RESULT_TASK_TYPE))
                    missionType = bundle.getInt(TaskFilterActivity.EXTRA_RESULT_TASK_TYPE);
                else
                    missionType = -1;

                if (bundle.containsKey(TaskFilterActivity.EXTRA_RESULT_USER_IDS))
                    userIds = bundle.getString(TaskFilterActivity.EXTRA_RESULT_USER_IDS) + "";
                else
                    userIds = null;

                if (bundle.containsKey(TaskFilterActivity.EXTRA_RESULT_PRIORITY))
                    priority = bundle.getInt(TaskFilterActivity.EXTRA_RESULT_PRIORITY);
                else
                    priority = -1;

                if (bundle.containsKey(TaskFilterActivity.EXTRA_RESULT_FINISH_TIME))
                    finishTime = bundle.getString(TaskFilterActivity.EXTRA_RESULT_FINISH_TIME) + "";
                else
                    finishTime = null;

                refreshData();
            }
        }
    }

    public void registerReceiver() {
        intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_REFRESH_LIST);
        intentFilter.addAction(ACTION_NEW_TASK_MSG);

        receiver = new TaskReceiver();
        registerReceiver(receiver, intentFilter);
    }

    enum ListType {
        FromMine, ToMe, CopyToMe;
    }

    class TaskReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_REFRESH_LIST)) {
                refreshData();
            } else if (intent.getAction().equals(ACTION_NEW_TASK_MSG)) {
                requestMsgCount();
            }
        }
    }
}
